<?php

namespace App\Http\Traits;

use App\Models\User;
use Auth;
use Gitlab\Client;
use Session;

trait GitLabTrait
{
    private $base_repo_url = 'ssh://git@git.linlaoban.com:2222/*.git';

    public function gitlabClient()
    {
        return new Client(env('GITLAB_API_URI'));
    }

    public function cacheGitLab()
    {
        /** @var User $user */
        $user = Auth::user();
        if ($user) {
            $client = $this->gitlabClient();
            if ($user->gitlab_private_token) {
                $client->authenticate($user->gitlab_private_token);
            } else {
                $client->authenticate($user->gitlab_access_token, Client::AUTH_OAUTH_TOKEN);
            }

            $gitlab_client = $client;
            Session::set('gitlab_client', $gitlab_client);

            return $this->getGitLab();
        }

        return false;
    }

    /**
     * @return bool|Client
     */
    public function getGitLab()
    {
        $gitlab_client = Session::get('gitlab_client');
        if (!$gitlab_client) {
            return $this->cacheGitLab();
        }

        return $gitlab_client;
    }

    public function getRealRepoUrl($namespace)
    {
        return str_replace('*', $namespace, $this->base_repo_url);
    }

    public function getRepoMembers($project_id)
    {
        return $this->members($project_id);
    }

    /**
     * @param int    $project_id
     * @param string $username_query
     *
     * @return mixed
     */
    public function members($project_id, $username_query = null)
    {
        try {
            $response = $this->getGitLab()->getHttpClient()->get($this->getProjectPath($project_id, 'members'), [
                'query' => $username_query,
            ]);

            return $response->getContent();
        } catch (\Exception $exception) {
            dump($this->getGitLab()->getHttpClient()->getLastRequest());
        }
    }

    protected function getProjectPath($id, $path, $per_page = 100, $page = 1)
    {
        return 'projects/' . $this->encodePath($id) . '/' . $path . '?' . http_build_query(['per_page' => $per_page, 'page' => $page]);
    }

    /**
     * @param string $path
     *
     * @return string
     */
    protected function encodePath($path)
    {
        $path = rawurlencode($path);

        return str_replace('.', '%2E', $path);
    }

    public function getGroupMembers($group_id, $page = 1, $per_page = 1000)
    {
        return $this->getGitLab()->groups->members($group_id, $page, $per_page);
    }

    public function getProject($project_id)
    {
        return $this->getGitLab()->projects->show($project_id);
    }

    public function getBranches($project_id)
    {
        return $this->getGitLab()->repositories->branches($project_id);
    }

    public function getTags($project_id)
    {
        return $this->getGitLab()->repositories->tags($project_id);
    }
}
